package com.yunduan.tornado.config.shiro;

import com.yunduan.tornado.entity.User;
import com.yunduan.tornado.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.Set;

@Slf4j
public class CustomRealm extends AuthorizingRealm {

    @Autowired
    private IUserService userService;
    /**
     *  权限验证
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //根据用户信息获取数据库权限集合
        String username = (String) SecurityUtils.getSubject().getPrincipal();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        Set<String> stringSet = new HashSet<>();
        stringSet.add("user:show");
        stringSet.add("user:admin");
        info.setStringPermissions(stringSet);
        log.info("权限=====================",stringSet);
        return info;
    }

    /**
     *  身份认证/登录  AuthenticationInfo（建议根据实际业务自己封装用户认证接口）
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
       //登录身份认证，根据用户登录token认证用户
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        //获取接口传的user账号信息
        String userName =  token.getUsername();
        //数据操作，根据用户账号查询用户信息，此处进行模拟数据操作
        //数据库的password
        User user = userService.selectUserByAccount(userName);
        //前台传送的password
        String passwod = new String (token.getPassword());
        //根据用户名从数据库获取密码
        if (user == null){
            throw new AccountException("用户不存在");
        }
        if (userName == null) {
            throw new AccountException("用户名不正确");
        } else if (!user.getPassword().equals(passwod )) {
            throw new AccountException("密码不正确");
        }
        return new SimpleAuthenticationInfo(user, passwod,getName());
    }


}
